package com.wewins.fota.aop;

import com.wewins.fota.common.constant.FotaCode;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.util.Arrays;

@Slf4j
@Component
@Aspect
@Order(2)
public class OperatorLogHandler {

    @Around(value = "@annotation(Operator)")
    public Object around(ProceedingJoinPoint joinPoint) {
        long start = System.currentTimeMillis();
        try {
            Object rst = joinPoint.proceed();
            String msg = getLogString(joinPoint, start);
            log.info(msg);
            return rst;
        } catch (Throwable throwable) {
            log.error("failed to record operator.", throwable);
            throwable.printStackTrace();
        }
        return null;
    }

    private String getLogString(ProceedingJoinPoint joinPoint, long start) {
        String msg = "DETAIL:" + Arrays.toString(joinPoint.getArgs());
        Operator operator = ((MethodSignature) joinPoint.getSignature()).getMethod().getAnnotation(Operator.class);
        if (operator != null) {
            FotaCode fotaCode = operator.value();
            msg = "TYPE:" + fotaCode.getCode() + ", SYMBOL:" + fotaCode.getMessage() + ", COST:" + (System.currentTimeMillis() - start) + "ms. " + msg;
        }
        return msg;
    }
}
